#include <Arduino.h>
#include "mqtt.h"
#include <PubSubClient.h>
#include <WiFi.h>
#include <ArduinoJson.h>
#include "wakeup.h"
#include "MyUdp.h"
#include "config.h"

WiFiClient espClient;
PubSubClient  client(espClient);
TaskHandle_t taskMqtt;
long lastMsg = 0;
 

static int parse_json(char *json, char *key, char *value)
{
  DynamicJsonDocument doc(1024);
  DeserializationError error = deserializeJson(doc, json);
  if (error) {
    Serial.print(F("deserializeJson() failed: "));
    Serial.println(error.c_str());
    return -1;
  }
   JsonObject obj = doc.as<JsonObject>();
  const char* temp = obj[key].as<const char*>();  // 使用 const char*
  if (temp != nullptr) {
    strcpy(value, temp);
    return 0;
  } 
  return -1;  // 键不存在或值为 null
  
}
static void mqtt_cb(char* topic, byte* payload, unsigned int length) {
  char macStr[18];
  char ipStr[16];
  Serial.print("Message arrived [");
  Serial.print(topic);   // 打印主题信息
  Serial.print("] ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]); // 打印主题内容
  }
  Serial.println();
  if(parse_json((char *)payload, "mac", (char *)macStr) != 0)
  {
    Serial.println("parse json mac error");
    return;
  }

  if(parse_json((char *)payload, "ip", (char *)ipStr) != 0)
  {
    Serial.println("parse json ip error");
    return;
  }


  // if(sendUDPPacket() == 0)
  // {
  //   // client.publish(MQTT_PUB_TOPIC, "wal ok"); 
  //   Serial.println("sendUDPPacket ok");
  // }
  // else
  // {
  //   // client.publish(MQTT_PUB_TOPIC, "wal error"); 
  //   Serial.println("sendUDPPacket error");
  // }


  if(wakeup(macStr,ipStr) == 0)
  {
    client.publish(MQTT_PUB_TOPIC, "wal ok"); 
    Serial.println("wal ok");
  }
  else
  {
    client.publish(MQTT_PUB_TOPIC, "wal error"); 
    Serial.println("wal error");
  }
  
}

void reconnect() {
  while (!client.connected()) {
    Serial.println("Attempting MQTT connection...");
    if (client.connect(MQTT_CLIENT_ID,MQTT_USRNAME,MQTT_PASSWD)) {
      Serial.println("connected");
      // 连接成功时订阅主题
      client.subscribe(MQTT_SUB_TOPIC);
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      delay(5000);
    }
  }
}

void mqtt_loopTask(void *pvParameters)
{
  
  while(1)
  {
    if (!client.connected() && WiFi.status() == WL_CONNECTED)
    {
      reconnect();
    }
    else if(client.connected() && WiFi.status() == WL_CONNECTED)
    {
      client.loop();
    }
    
    delay(5);
  }
  
}

void mqtt_setup()
{
  client.setServer(MQTT_SERVER, MQTT_PORT); //设定MQTT服务器与使用的端口，1883是默认的MQTT端口
  client.setCallback(mqtt_cb);             //设定回调方式，当ESP8266收到订阅消息时会调用此方法
}



